import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_animations/flutter_map_animations.dart';
import 'package:flutter_map_test/pages/map/map_test_controller.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';

class MapView extends GetView<MapTestController> {
  const MapView({super.key});

  List<Polyline<Object>> _randomTracks() {
    const int testCount = 100; // 轨迹总数
    const int columnCount = 50; // 每列显示数量
    const double rowSpacing = 0.00002; // 行间距
    const double colSpacing = 0.0016; // 列间距
    const double radius = 0.0005; // 基础半径
    const double petalCount = 5; // 花瓣数量
    const double petalScale = 0.6; // 花瓣大小比例

    final List<Polyline> list = [];

    for (int i = 0; i < testCount; i++) {
      // 计算行列索引（矩阵布局）
      final int col = i ~/ columnCount;
      final int row = i % columnCount;

      // 生成渐变颜色（基于索引）
      final Color color = Color.fromARGB(
          255,
          (i * 5) % 255, // R通道
          (i * 10) % 255, // G通道
          (i * 15) % 255 // B通道
          );

      // 计算基础坐标（矩阵排列）
      final double baseLat = 39.9042 + row * rowSpacing;
      final double baseLng = 116.4074 + col * colSpacing;

      // 生成1000个点的玫瑰线轨迹
      final List<LatLng> points = [];
      for (int j = 0; j < 1000; j++) {
        // 计算角度（0-2π均匀分布）
        final double angle = j * (2 * math.pi / 1000);

        // 玫瑰线方程：r = a(1 + cos(nθ))
        final double dynamicRadius =
            radius * (1 + petalScale * math.cos(petalCount * angle));

        // 计算坐标（极坐标转直角坐标）
        points.add(LatLng(
          baseLat + math.sin(angle) * dynamicRadius,
          baseLng + math.cos(angle) * dynamicRadius,
        ));
      }

      // 添加轨迹线
      list.add(Polyline(
          points: points,
          color: color,
          strokeWidth: 2,
          pattern: StrokePattern.dashed(segments: const [5, 5])));
    }

    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ValueListenableBuilder<List<AnimatedMarker>>(
            valueListenable: controller.markers,
            builder: (context, markers, _) {
              return FlutterMap(
                mapController: controller.mapCtl.mapController,
                options: MapOptions(
                  initialCenter: controller.center.value,
                  initialZoom: 13,
                  cameraConstraint: CameraConstraint.contain(
                    bounds: LatLngBounds(
                      const LatLng(-90, -180),
                      const LatLng(90, 180),
                    ),
                  ),
                  initialCameraFit: CameraFit.bounds(
                    bounds: LatLngBounds(
                      // 根据CircleMarker中心点和半径计算西南角
                      LatLng(
                        39.916527 - (1000 / 111319.9),  // 纬度偏移 = 半径(米)/111319.9(米/度)
                        116.397128 - (1000 / (111319.9 * math.cos(39.916527 * math.pi / 180)))
                      ),
                      // 根据CircleMarker中心点和半径计算东北角
                      LatLng(
                        39.916527 + (1000 / 111319.9),
                        116.397128 + (1000 / (111319.9 * math.cos(39.916527 * math.pi / 180)))
                      ),
                    ),
                    padding: const EdgeInsets.all(20),
                  ),
                  interactionOptions: const InteractionOptions(
                    flags: InteractiveFlag.all & ~InteractiveFlag.rotate,
                    rotationThreshold: 1000,
                    pinchZoomWinGestures: InteractiveFlag.drag,
                    pinchZoomThreshold: 0.3, // 降低缩放触发阈值（更灵敏）
                    pinchMoveThreshold: 20.0, // 降低平移触发阈值
                    enableMultiFingerGestureRace: false, // 禁用手势竞争（更稳定）
                  ),
                  backgroundColor: Colors.grey,
                  onMapReady: () => {
                    // print("地图初始化完成==${controller.mapCtl}"),
                    controller.isReady = true,
                  },
                  onMapEvent: (MapEvent e) {
                    // print("看看地图控制器里都有啥==${controller.mapCtl.mapEventStream}");
                    // print("像素边界==${controller.mapCtl.camera.pixelBounds}");
                    // print("像素中心==${controller.mapCtl.camera.pixelOrigin}");
                    // final point = controller.mapCtl.camera.project(LatLng(39.916527, 116.397128));
                    // print("什么是坐标投影转换==${point}");
                    // print("center===${e.camera.center}");
                    // print("zoom===${e.camera.zoom}");
                  },
                ),
                children: [
                  TileLayer(
                    urlTemplate:
                        'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
                  ),
                  PolylineLayer(
                    polylines: [
                      ..._randomTracks(),
                    ],
                  ),
                  MarkerLayer(
                    markers: [
                      const Marker(
                        point: LatLng(39.91, 116.39),
                        alignment: Alignment(3, 0),
                        child: Icon(
                          Icons.access_alarms_outlined,
                          color: Colors.pink,
                          size: 40,
                        ),
                      ),
                      Marker(
                          point: const LatLng(39.916527, 116.397128),
                          child: Obx(() => Transform.rotate(
                                angle: controller.compassAngle.value,
                                child: const Icon(
                                  Icons.navigation,
                                  color: Colors.red,
                                  size: 40,
                                ),
                              ))),
                    ],
                  ),
                  const CircleLayer(
                    circles: [
                      CircleMarker(
                        point: LatLng(39.916527, 116.397128),
                        radius: 1000,
                        useRadiusInMeter: true,
                        color: Color.fromRGBO(0, 255, 0, 0.1),
                        borderStrokeWidth: 1,
                        borderColor: Colors.green,
                      ),
                    ],
                  ),
                ],
              );
            }));
  }
}
